package io.renren.modules.generator.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import io.renren.common.validator.Assert;
import io.renren.modules.generator.entity.CrewInfoEntity;
import io.renren.modules.generator.entity.ExperienceInfoEntity;
import io.renren.modules.generator.service.CrewInfoService;
import io.renren.modules.generator.service.ExperienceInfoService;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;


/**
 * 船员基本信息表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2019-10-19 11:58:04
 */
@Api(tags = "船员基本信息表")
@RestController
@RequestMapping("generator/crewinfo")
public class CrewInfoController extends ShiroUtils {
    @Autowired
    private CrewInfoService crewInfoService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ExperienceInfoService experienceInfoService;

    /**
     * 列表
     */
    @ApiOperation("列表")
    @GetMapping("/list")
    @RequiresPermissions("generator:crewinfo:list")
    public R list(@RequestParam Map<String, Object> params) {

        //如果不是超级管理员，则只查询自己所拥有的角色列表
    /*    if(getUserId() != Constant.SUPER_ADMIN){
            Long userId= ShiroUtils.getUserId();
            params.put("userId",userId);
        }*/
        //1.每个人登录后，有userid
        Long userId = ShiroUtils.getUserId();
        //2.查询该userid的companyid
        Optional.ofNullable(sysUserService.getOne(
                new QueryWrapper<SysUserEntity>().lambda().eq(SysUserEntity::getUserId, userId)))
                .filter(f -> f.getAffiliatedCompanyId() != null)
                .map(m -> params.put("companyId", m.getAffiliatedCompanyId()));
        //3.再用companyid查询合同表的数据，派遣表的数据，船员表的数据
        PageUtils page = crewInfoService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 船员列表
     */
    @ApiOperation("船员列表")
    @GetMapping("/select")
//    @RequiresPermissions("generator:crewinfo:select")
    public R select() {
        Map<String, Object> map = new HashMap<>();

        SysUserEntity user = ShiroUtils.getUserEntity();
        Long affiliated_company_id = user.getAffiliatedCompanyId();

        //如果不是超级管理员，则只查询自己所拥有的角色列表
        if (getUserId() != Constant.SUPER_ADMIN) {
            map.put("affiliated_company_id", affiliated_company_id);
        }
        List<CrewInfoEntity> list = (List<CrewInfoEntity>) crewInfoService.listByMap(map);

        return R.ok().put("list", list);
    }

    /**
     * 信息
     */
    @ApiOperation("船员信息")
    @GetMapping("/info/{crewId}")
    @RequiresPermissions("generator:crewinfo:info")
    public R info(@PathVariable("crewId") Long crewId) {
        CrewInfoEntity crewInfo = crewInfoService.getById(crewId);
        //插入list
        HashMap map = new HashMap();
        map.put("crew_id", crewId);
        List<ExperienceInfoEntity> experienceList =
                (List<ExperienceInfoEntity>) experienceInfoService.listByMap(map);
        crewInfo.setExperience_list(experienceList);
        return R.ok().put("crewInfo", crewInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("generator:crewinfo:save")
    public R save(@RequestBody CrewInfoEntity crewInfo, HttpServletRequest request) {

        SysUserEntity user = ShiroUtils.getUserEntity();
        Long createUserId = user.getUserId();
        //如果是系统管理员，提示一下
        Optional.ofNullable(user).filter(f -> f.getAffiliatedCompanyId() != null)
                .orElseThrow(() -> new RRException("该登录用户还没绑定公司"));
        //设置IP地址
        crewInfo.setCreateUserIp(IPUtils.getIpAddr(request));
        crewInfo.setCreateTime(new Date());
        crewInfo.setCreateUserId(createUserId);
        crewInfo.setAffiliatedCompanyId(user.getAffiliatedCompanyId());

        crewInfoService.save(crewInfo);
        crewInfo.getExperience_list().forEach(l -> {
            l.setCrewId(crewInfo.getCrewId());
            experienceInfoService.save(l);
        });

        return R.ok();
    }

    /**
     * 修改
     */
    @ApiOperation("船员修改")
    @PostMapping("/update")
    @RequiresPermissions("generator:crewinfo:update")
    public R update(@RequestBody CrewInfoEntity crewInfo) {
        crewInfoService.updateById(crewInfo);

        crewInfo.getExperience_list().forEach(l -> {
            l.setCrewId(crewInfo.getCrewId());
            experienceInfoService.saveOrUpdate(l);
        });

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("generator:crewinfo:delete")
    public R delete(@RequestBody Long[] crewIds) {
        crewInfoService.removeByIds(Arrays.asList(crewIds));

        return R.ok();
    }

    /**
     * 新增履历
     */
    @PostMapping("saveExperience")
    public R saveExperience(@RequestBody ExperienceInfoEntity experienceInfoEntity) {
        experienceInfoService.save(experienceInfoEntity);
        return R.ok();
    }

    /**
     * 删除单条履历
     */
    @PostMapping("deleteExperience")
    public R deleteExperience(@RequestBody Long workExperienceId) {
        Assert.isNull(workExperienceId, "履历id不能为空");
        experienceInfoService.removeById(workExperienceId);
        return R.ok();
    }

    /**
     * 导出word文档，响应到请求端
     *
     * @param tempName，要使用的模板
     * @param docName，导出文档名称
     * @param dataMap，模板中变量数据
     * @param resp,HttpServletResponse
     */
    public boolean exportDoc(String tempName, String docName, Map<?, ?> dataMap, HttpServletResponse resp) {
        boolean status = false;
        ServletOutputStream sos = null;
        InputStream fin = null;
        if (resp != null) {
            resp.reset();
        }

        // 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet，classpath，数据库装载。参数2为模板路径
//        configuration.setClassForTemplateLoading(this.getClass(), "/templates/");
        Configuration configuration = new Configuration(new Version("2.3.0"));
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(CrewInfoController.class, "/templates/");

        Template t = null;

        try {
            // tempName.ftl为要装载的模板
            t = configuration.getTemplate(tempName + ".ftl");
            t.setEncoding("utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 输出文档路径及名称 ,以临时文件的形式导出服务器，再进行下载
        String name = "temp" + (int) (Math.random() * 100000) + ".doc";
        File outFile = new File(name);

        Writer out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
            status = true;
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        try {
            t.process(dataMap, out);
            out.close();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            fin = new FileInputStream(outFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 文档下载
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/msword");
        try {
            docName = new String(docName.getBytes("UTF-8"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        resp.setHeader("Content-disposition", "attachment;filename=" + docName + ".doc");
        try {
            sos = resp.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] buffer = new byte[512]; // 缓冲区
        int bytesToRead = -1;
        // 通过循环将读入的Word文件的内容输出到浏览器中
        try {
            while ((bytesToRead = fin.read(buffer)) != -1) {
                sos.write(buffer, 0, bytesToRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fin != null)
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (sos != null)
                try {
                    sos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (outFile != null)
                outFile.delete(); // 删除临时文件
        }

        return status;
    }

    @ApiOperation("渤海轮渡简历表")
    @GetMapping("export1")
    public void export1(Long crewId, HttpServletResponse resp) {
        CrewInfoEntity crewInfo = crewInfoService.getById(crewId);
        Map<String, Object> map = new HashMap<>();

        //基本信息
        if (crewInfo.getSex() == 0) {
            map.put("sex", "男");
        } else {
            map.put("sex", "女");
        }
        map.put("crewInfo", crewInfo);

        //履历
        HashMap exMap = new HashMap();
        exMap.put("crew_id", crewId);
        List<ExperienceInfoEntity> experienceList = (List<ExperienceInfoEntity>) experienceInfoService.listByMap(exMap);
        map.put("experienceList", experienceList);

        exportDoc("0001", "渤海轮渡简历表", map, resp);
    }

    @ApiOperation("社会船员面试及信息登记表")
    @GetMapping("export2")
    public void export2(Long crewId, HttpServletResponse resp) {
        CrewInfoEntity crewInfo = crewInfoService.getById(crewId);
        Map<String, Object> map = new HashMap<>();

        //基本信息
        if (crewInfo.getSex() == 0) {
            map.put("sex", "男");
        } else {
            map.put("sex", "女");
        }
        map.put("crewInfo", crewInfo);

        //履历
        HashMap exMap = new HashMap();
        exMap.put("crew_id", crewId);
        List<ExperienceInfoEntity> experienceList = (List<ExperienceInfoEntity>) experienceInfoService.listByMap(exMap);
        map.put("experienceList", experienceList);

        exportDoc("0002", "社会船员面试及信息登记表", map, resp);
    }

    @ApiOperation("中远海运专用简历")
    @GetMapping("export3")
    public void export3(Long crewId, HttpServletResponse resp) {
        CrewInfoEntity crewInfo = crewInfoService.getById(crewId);
        Map<String, Object> map = new HashMap<>();

        //基本信息
        if (crewInfo.getSex() == 0) {
            map.put("sex", "男");
        } else {
            map.put("sex", "女");
        }
        map.put("crewInfo", crewInfo);

        //履历
        HashMap exMap = new HashMap();
        exMap.put("crew_id", crewId);
        List<ExperienceInfoEntity> experienceList = (List<ExperienceInfoEntity>) experienceInfoService.listByMap(exMap);
        map.put("experienceList", experienceList);

        exportDoc("0003", "中远海运专用简历", map, resp);
    }

    @ApiOperation("海员简历表")
    @GetMapping("export4")
    public void export4(Long crewId, HttpServletResponse resp) {
        CrewInfoEntity crewInfo = crewInfoService.getById(crewId);
        Map<String, Object> map = new HashMap<>();

        //基本信息
        if (crewInfo.getSex() == 0) {
            map.put("sex", "男");
        } else {
            map.put("sex", "女");
        }
        map.put("crewInfo", crewInfo);

        //履历
        HashMap exMap = new HashMap();
        exMap.put("crew_id", crewId);
        List<ExperienceInfoEntity> experienceList = (List<ExperienceInfoEntity>) experienceInfoService.listByMap(exMap);
        map.put("experienceList", experienceList);

        exportDoc("0004", "海员简历表", map, resp);
    }

}
